﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms.Integration;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace HYView
{
	public class Family3DViewHelper
	{
		private void Update3DView(Autodesk.Revit.DB.Document subdoc, ElementHost elementHost)
		{
			PreviewControl previewControl = elementHost.Child as PreviewControl;
			if (subdoc == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(subdoc);
			filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View));
			IEnumerable<Autodesk.Revit.DB.View> enumerable = from Element f in filteredElementCollector
			where (f as Autodesk.Revit.DB.View).CanBePrinted
			select f as Autodesk.Revit.DB.View;
			Autodesk.Revit.DB.View view = null;
			foreach (Autodesk.Revit.DB.View view2 in enumerable)
			{
				if ((int)view2.ViewType == 4 && view2.Name == "{3D}")
				{
					view = view2;
					break;
				}
			}
			if (view == null)
			{
				foreach (Autodesk.Revit.DB.View view3 in enumerable)
				{
					if ((int)view3.ViewType == 4)
					{
						view = view3;
						break;
					}
				}
			}
			if (view == null)
			{
				foreach (Autodesk.Revit.DB.View view4 in enumerable)
				{
					if ((int)view4.ViewType == 1)
					{
						view = view4;
						break;
					}
				}
			}
			if (view == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			if (previewControl != null)
			{
				previewControl.Dispose();
			}
			elementHost.Child = new PreviewControl(subdoc, view.Id);
		}

		public void InitPreviewControl(Autodesk.Revit.DB.Document doc, FamilySymbol fs, ElementHost elementHost)
		{
			Document subdoc = doc.EditFamily(fs.Family);
			this.Update3DView(subdoc, elementHost);
		}
	}
}
